import { notice, utilities } from '@/utils/common.js'
import {
	getFlowInfo,
	getFormData,
	getStartScript,
	getInitScript,
	startFlowExpand,
	StartFlowByVariable,
	endFlow as doEndProcess,
	agreeFlow as agree,
	opposeFlow as oppose,
	rejectFlow as reject,
	backStarter as rejectToStarter,
	previous as rejectToPrevious,
} from '@/api/base/flow.js'

export default {
	data() {
		return {
			taskId: '',
			nodeId: '',
			nodeName: '',
			procDefKey: '',
			flowBtn: {},
			opinion: '',
			buttons: [],
			isMore: false,
			moreBtns: [],
			variableMap: {},
			flowParams: {},
			// 是否需要事务
			transFlag: false,
			startButtons: [],
			startFlowTotal : 0,
			startButtonFlag:false,
			useStartFlowParams: 'nodeUsers',
			startFlowParams: {},
			defaultStartData:{
				exeId: '',
				exename: '',
				exetype: "employee",
				groupType: "",
				executors: [],
				flowParam: {}
			},
			startRequest: {}, // 流程请求对象
		}
	},
	methods: {
		// 处理初始化脚本
		async handleScrpitData(flowKey) {
			if (flowKey !== '') {
				await getStartScript(flowKey).then(response => {
					const result = response.data
					if (result.script !== null) {
						if (result.script.INITFORMSCRIPT) {
							let scriptData = eval('(' + result.script.INITFORMSCRIPT + ')')
							if (scriptData.disable_data) {
								scriptData.disable_data.forEach((item, index) => {
									this.disableData.push(item)
								})
							}
							if (scriptData.show_data) {
								scriptData.show_data.forEach((item, index) => {
									this.disableData = this.disableData.filter(t => t != item)
								})
							}

							if (scriptData.edit_data) {
								scriptData.edit_data.forEach((item, index) => {
									this.readOnlyData = this.readOnlyData.filter(t => t != item)
								})
							}
							if (scriptData.readOnly_data) {
								scriptData.readOnly_data.forEach((item, index) => {
									this.readOnlyData.push(item)
								})
							}

							if (scriptData.require_data) {
								this.requireData = scriptData.require_data
							}

							if (scriptData.init_data) {
								this.initData = scriptData.init_data
							}
						}
					}

					if (result.buttons !== null) {
						this.startButtons = result.buttons
					}
				})
			}
		},
		// 流程启动前置脚本
		async doStartFlowBeforeScript() {
			let that = this
			for (let i = 0; i < that.startButtons.length; i++) {
				let key = 'startFlow'
				if (that.startButtons[i].alias === key) {
					let scriptStr = that.startButtons[i].beforeScript
					if (scriptStr === '') {
						return true
					}
					try {
						let doFunction = eval('(' + scriptStr + ')')
						await doFunction()
						return true
					} catch (e) {
						notice.toast(e.message)
						return false
					}
				}
			}
		},
		// 启动流程
		startFlow() {
			this.doStartFlowBeforeScript().then(res => {
				if (res) {
					this.startFlowTotal = this.startFlowTotal + 1
					this.start()
				}
			})
		},
		async flowStart(bizId, formKey, defKey) {
			let result
			if (Object.keys(this.defaultStartData.flowParam).length > 0) {
				this.startRequest.flowParam = encodeURI(encodeURI(JSON.stringify(this.defaultStartData.flowParam)).replace(/&/g, '%26').replace(/\+/g, '%2B').replace(/\s/g, '%20').replace(/#/g, '%23'))
			}
			if (this.startRequest.destination && this.defaultStartData.executors.length > 0) {
				let nodeObj = [
					{
						nodeId: this.startRequest.destination,
						executors: [] // 执行人信息
					}
				]
				nodeObj[0].executors = this.defaultStartData.executors
				this.startRequest.nodeUsers = JSON.stringify(nodeObj)
			}
			this.startRequest.defKey = defKey
			this.startRequest.formKey = formKey
			this.startRequest.ids = bizId
			await startFlowExpand(this.startRequest).then(res => {
				result = res.state
				if(res.state === 200){
					notice.success(this.$t('ticket.message.processStartedSuccess'))
					this.doStartFlowAfterScript()
				} else {
					this.startFlowTotal = 0
					notice.toast(this.$t('ticket.message.processStartedFailed') + ":" + res.message + " - " + res.cause)
				}
			})
			
			// // 使用nodeUsers脚本启动流程
			// if(this.useStartFlowParams === 'nodeUsers'){
			// 	this.startFlowParams = {
			// 		defKey: defKey,
			// 		formKey: formKey,
			// 		ids: bizId,
			// 		flowParam: encodeURI(encodeURI(JSON.stringify(this.defaultStartData.flowParam))),
			// 		nodeUsers: JSON.stringify([{
			// 			nodeId: this.defaultStartData.nodeId,
			// 			executors: this.defaultStartData.executors
			// 		}])
			// 	}
				
			// 	await startFlowExpand(this.startFlowParams).then(res => {
			// 		result = res.state
			// 		if(res.state === 200){
			// 			notice.success(this.$t('ticket.message.processStartedSuccess'))
			// 			this.doStartFlowAfterScript()
			// 		} else {
			// 			this.startFlowTotal = 0
			// 			notice.toast(this.$t('ticket.message.processStartedFailed') + ":" + res.message + " - " + res.cause)
			// 		}
			// 	})
			// }
			
			// // 使用变量脚本启动流程
			// if(this.useStartFlowParams === 'variable') {
			// 	this.startFlowParams = {
			// 		defKey: defKey,
			// 		formKey: formKey,
			// 		ids: bizId,
			// 		destination: this.defaultStartData.nodeId,
			// 		flowParam: encodeURI(encodeURI(JSON.stringify(this.defaultStartData.flowParam))),
			// 	}
			// 	await StartFlowByVariable(this.startFlowParams).then(res => {
			// 		result = res.state
			// 		if(res.state === 200){
			// 			notice.success(this.$t('ticket.message.processStartedSuccess'))
			// 			this.doStartFlowAfterScript()
			// 		} else {
			// 			this.startFlowTotal = 0
			// 			notice.toast(this.$t('ticket.message.processStartedFailed') + ":" + res.message + " - " + res.cause)
			// 		}
			// 	})
			// }
			return result
		},
		// 流程启动后置方法
		async doStartFlowAfterScript() {
			for (let i = 0; i < this.startButtons.length; i++) {
				let key = 'startFlow'
				if (this.startButtons[i].alias === key) {
					let scriptStr = this.startButtons[i].beforeScript
					if (scriptStr === '') {
						return true
					}
					let that = this
					try {
						let doFunction = eval('(' + scriptStr + ')')
						await doFunction()
						return true
					} catch (e) {
						notice.toast(e.message)
						return false
					}
				}
			}
		},
		// 更新流程启动参数(flowVariable)
		updateStartFlowByVariable(flowVariableY, formFieldY, flowVariableN, formFieldN, expression) {
			let variableMap = ''
			let flowVariableParam = null
			if (typeof expression === 'undefined') {
				if (formFieldY.indexOf('defaultData') != -1 || formFieldY.indexOf('formData') != -1) {
					if (formFieldY.indexOf('formData') != -1) {
						formFieldY = formFieldY.replace(/formData./g, '')
						variableMap = this.formData[formFieldY]
					}
					if (formFieldY.indexOf('defaultData') != -1) {
						formFieldY = formFieldY.replace(/defaultData./g, '')
						variableMap = this.defaultData[formFieldY]
					}
				} else {
					variableMap = formFieldY
				}
				flowVariableParam = { [flowVariableY]: variableMap }
			} else {
				if (expression.indexOf('formData') != -1 && expression.indexOf('defaultData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
					expression = expression.replace(/defaultData/g, 'that.defaultData')
				} else if (expression.indexOf('defaultData') != -1) {
					expression = expression.replace(/defaultData/g, 'that.defaultData')
				} else if (expression.indexOf('formData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
				}
				let that = this
				let conditional = eval(expression)
				if (conditional) {
					if (formFieldY.indexOf('defaultData') != -1 || formFieldY.indexOf('formData') != -1) {
						if (formFieldY.indexOf('formData') != -1) {
							formFieldY = formFieldY.replace(/formData./g, '')
							variableMap = this.formData[formFieldY]
						}
						if (formFieldY.indexOf('defaultData') != -1) {
							formFieldY = formFieldY.replace(/defaultData./g, '')
							variableMap = this.defaultData[formFieldY]
						}
					} else {
						variableMap = formFieldY
					}
					flowVariableParam = { [flowVariableY]: variableMap }
				} else {
					if (formFieldN.indexOf('defaultData') != -1 || formFieldN.indexOf('formData') != -1) {
						if (formFieldN.indexOf('formData') != -1) {
							formFieldN = formFieldN.replace(/formData./g, '')
							variableMap = this.formData[formFieldN]
						}
						if (formFieldN.indexOf('defaultData') != -1) {
							formFieldN = formFieldN.replace(/defaultData./g, '')
							variableMap = this.defaultData[formFieldN]
						}
					} else {
						if (flowVariableN != '' && flowVariableN != null) {
							variableMap = formFieldN
						}
					}
					if (flowVariableN != '' && flowVariableN != null) {
						flowVariableParam = { [flowVariableN]: variableMap }
					}
				}
			}
			if (flowVariableParam != null) {
				this.defaultStartData.flowParam = Object.assign(this.defaultStartData.flowParam, flowVariableParam)
				this.defaultStartData.useStartFlowParams = 'variable'
			}
		},
		// 更新流程变量
		updateStartFlowByVariableSubStr(flowVariableY, formFieldY, subRuleY, flowVariableN, formFieldN, subRuleN, expression) {
			let variableMap = ''
			let flowVariableParam = null
			if (typeof expression === 'undefined') {
				if (formFieldY.indexOf('defaultData') != -1 || formFieldY.indexOf('formData') != -1) {
					if (formFieldY.indexOf('formData') != -1) {
						formFieldY = formFieldY.replace(/formData./g, '')
						variableMap = this.formData[formFieldY]
					}
					if (formFieldY.indexOf('defaultData') != -1) {
						formFieldY = formFieldY.replace(/defaultData./g, '')
						variableMap = this.defaultData[formFieldY]
					}
				} else {
					variableMap = formFieldY
				}
				if(subRuleY.indexOf('left') != -1) {
					let N = subRuleY.split(":")[1]
					variableMap = variableMap.substr(0,N)
				}
				if(subRuleY.indexOf('right') != -1) {
					let N = subRuleY.split(":")[1]
					variableMap = variableMap.substr(N,variableMap.length)
				}
				if(subRuleY.indexOf('index') != -1) {
					let N = subRuleY.split(":")[1]
					let varArr = variableMap.split(",")
					if (varArr.length > N) {
						variableMap = variableMap.split(",")[N]
					} else {
						variableMap = variableMap.split(",")[varArr.length - 1]
					}
				}
				flowVariableParam = { [flowVariableY]: variableMap }
			} else {
				if (expression.indexOf('formData') != -1 && expression.indexOf('defaultData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
					expression = expression.replace(/defaultData/g, 'that.defaultData')
				} else if (expression.indexOf('defaultData') != -1) {
					expression = expression.replace(/defaultData/g, 'that.defaultData')
				} else if (expression.indexOf('formData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
				}
				let that = this
				let conditional = eval(expression)
				if (conditional) {
					if (formFieldY.indexOf('defaultData') != -1 || formFieldY.indexOf('formData') != -1) {
						if (formFieldY.indexOf('formData') != -1) {
							formFieldY = formFieldY.replace(/formData./g, '')
							variableMap = this.formData[formFieldY]
						}
						if (formFieldY.indexOf('defaultData') != -1) {
							formFieldY = formFieldY.replace(/defaultData./g, '')
							variableMap = this.defaultData[formFieldY]
						}
					} else {
						variableMap = formFieldY
					}
					if(subRuleY.indexOf('left') != -1) {
						let N = subRuleY.split(":")[1]
						variableMap = variableMap.substr(0,N)
					}
					if(subRuleY.indexOf('right') != -1) {
						let N = subRuleY.split(":")[1]
						variableMap = variableMap.substr(N,variableMap.length)
					}
					if(subRuleY.indexOf('index') != -1) {
						let N = subRuleY.split(":")[1]
						variableMap = variableMap.split(",")[N]
					}
					flowVariableParam = { [flowVariableY]: variableMap }
				} else {
					if (formFieldN.indexOf('defaultData') != -1 || formFieldN.indexOf('formData') != -1) {
						if (formFieldN.indexOf('formData') != -1) {
							formFieldN = formFieldN.replace(/formData./g, '')
							variableMap = this.formData[formFieldN]
						}
						if (formFieldN.indexOf('defaultData') != -1) {
							formFieldN = formFieldN.replace(/defaultData./g, '')
							variableMap = this.defaultData[formFieldN]
						}
					} else {
						if(flowVariableN != "" && flowVariableN != null) {
							variableMap = formFieldN
						}
					}
					if(flowVariableN != "" && flowVariableN != null) {
						if(subRuleN.indexOf('left') != -1){
							let N = subRuleN.split(":")[1]
							variableMap = variableMap.substr(0,N)
						}
						if(subRuleN.indexOf('right') != -1) {
							let N = subRuleN.split(":")[1]
							variableMap = variableMap.substr(N,variableMap.length)
						}
						if(subRuleN.indexOf('index') != -1) {
							let N = subRuleN.split(":")[1]
							variableMap = variableMap.split(",")[N]
						}
						flowVariableParam = { [flowVariableN]: variableMap }
					}
				}
			}
			if(flowVariableParam != null) {
				this.defaultStartData.flowParam = Object.assign(this.defaultStartData.flowParam, flowVariableParam)
				this.useStartFlowParams = 'variable'
			}
		},
		// 更新流程启动参数(nodeUsers)
		updateStartFlowByNodeUsers(nodeId, formField, formFieldName, expression) {
			let variableMap = ''
			let variableName = ''
			if (typeof expression === 'undefined') {
				if (formField.indexOf('defaultData') != -1 || formField.indexOf('formData') != -1) {
					if (formField.indexOf('formData') != -1) {
						formField = formField.replace(/formData./g, '')
						variableMap = this.formData[formField]
					}
		 		if (formField.indexOf('defaultData') != -1) {
						formField = formField.replace(/defaultData./g, '')
						variableMap = this.defaultStartData[formField]
					}
				} else {
					variableMap = formField
				}
				if (formFieldName.indexOf('defaultData') != -1 || formFieldName.indexOf('formData') != -1) {
					if (formFieldName.indexOf('formData') != -1) {
						formFieldName = formFieldName.replace(/formData./g, '')
						variableName = this.formData[formFieldName]
					}
					if (formFieldName.indexOf('defaultData') != -1) {
						formFieldName = formFieldName.replace(/defaultData./g, '')
						variableName = this.defaultStartData[formFieldName]
					}
				} else {
					variableName = formFieldName
				}
			} else {
				if (expression.indexOf('formData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
				}
				let that = this
				let conditional = eval(expression)
				if (conditional) {
					if (formField.indexOf('defaultData') != -1 || formField.indexOf('formData') != -1) {
						if (formField.indexOf('formData') != -1) {
							formField = formField.replace(/formData./g, '')
							variableMap = this.formData[formField]
						}
						if (formField.indexOf('defaultData') != -1) {
							formField = formField.replace(/defaultData./g, '')
							variableMap = this.defaultStartData[formField]
						}
					} else {
						variableMap = formField
					}

					if (formFieldName.indexOf('defaultData') != -1 || formFieldName.indexOf('formData') != -1) {
						if (formFieldName.indexOf('formData') != -1) {
							formFieldName = formFieldName.replace(/formData./g, '')
							variableName = this.formData[formFieldName]
						}
						if (formFieldName.indexOf('defaultData') != -1) {
							formFieldName = formFieldName.replace(/defaultData./g, '')
							variableName = this.defaultStartData[formFieldName]
						}
					} else {
						variableName = formFieldName
					}
				}
			}
			this.defaultStartData.exeId = variableMap
			this.defaultStartData.exeName = variableName
			this.defaultStartData.nodeId = nodeId
			let executor = {
				id: this.defaultStartData.exeId,
				type: this.defaultStartData.exetype,
				name: this.defaultStartData.exeName,
				groupType: this.defaultStartData.groupType
			}
			this.defaultStartData.executors.push(executor)
			this.useStartFlowParams = 'nodeUsers'
		},
		/**
		 * 获取流程信息
		 * @param bizKey 业务主键
		 */
		async getFlowTaskInfo(bizKey) {
			// 获取流程任务ID
			await getFlowInfo(bizKey).then(res => {
				this.taskId = res.data.dataResult.length > 0 ? res.data.dataResult[0].taskId : ""
				this.nodeId = res.data.dataResult.length > 0 ? res.data.dataResult[0].nodeId : ""
				this.nodeName = res.data.dataResult.length > 0 ? res.data.dataResult[0].name : ""
				this.procDefKey = res.data.dataResult.length > 0 ? res.data.dataResult[0].procDefKey : ""
			})

			if (this.taskId) {
				// 获取任务表单的详情
				let executors = []
				await getFormData(this.taskId).then(res => {
					res.data.attributes.opinionList.forEach(item => {
						if (this.nodeId === item.taskKey) {
							item.qualifiedExecutor.forEach(user => {
								executors.push(user.executId)
							})
						}
					})
				})

				// 获取流程脚本
				await getInitScript(this.taskId).then(res => {
					this.buttons = []
					// 流程按钮-移动端只筛选出同意、驳回、自定义类型的按钮
					for (let i = 0; i < res.data.buttons.length; i++) {
						const button = res.data.buttons[i]
						// 流程实例信息、流程图、审批历史、打印、缺陷的工单策划 移动端不需要
						if (button.alias != 'instanceDetail' && button.alias != 'flowImage' &&
							button.alias != 'approvalHistory' && button.alias != 'print' &&
							button.code != 'run_print_zj' && button.code != 'run_print' &&
							executors.includes(this.defaultData.userId)) {
							const alias = button.alias
							const code = button.code
							button.key = alias === 'custom' ? (code || (alias + i)) : alias
							this.buttons.push(button)
						}
					}

					// 多个按钮处理
					if (this.buttons.length > 3) {
						this.isMore = true
						this.moreBtns = this.buttons.slice(2, this.buttons.length)
						this.buttons = this.buttons.splice(0, 2)
					}

					// 流程初始化脚本
					if (res.data.script !== null) {
						if (res.data.script.INITFORMSCRIPT) {
							let initFormScript = eval('(' + res.data.script.INITFORMSCRIPT + ')')
							
							if(initFormScript.disable_data !== undefined) {
								initFormScript.disable_data.forEach(item => {
									this.disableData.push(item)
								})
							}
							if(initFormScript.show_data !== undefined) {
								initFormScript.show_data.forEach(item => {
									this.disableData = this.disableData.filter(t => t != item)
								})
							}

							if(initFormScript.edit_data !== undefined) {
								initFormScript.edit_data.forEach(item => {
									if(this.readOnlyData == undefined) {
										this.editData.push(item)
									} else {
										this.readOnlyData = this.readOnlyData.filter(t => t != item)
									}
								})
							}
							if(initFormScript.readOnly_data !== undefined) {
								initFormScript.readOnly_data.forEach(item => {
									if(this.readOnlyData == undefined) {
										this.editData = this.editData.filter(t => t != item)
									} else {
										this.readOnlyData.push(item)
									}
								})
							}
							
							this.initData = initFormScript.init_data !== undefined ? initFormScript.init_data : []
							this.requireData = initFormScript.require_data !== undefined ? initFormScript.require_data : []
						}
					}
				})
			}
		},
		// 初始化默认数据
		loadDefaultData() {
			this.defaultData.userId = uni.getStorageSync("userId")
			this.defaultData.userName = uni.getStorageSync("userName")
			this.defaultData.date = utilities.getNowDate()
			this.defaultData.dateTime = utilities.getNowDateTime()
		},
		// 初始化数据
		loadInitData() {
			this.initData.forEach(item => {
				let that = this
				if (typeof item.value === 'boolean') {
					let fieldStr = 'that.' + item.field + "= " + item.value
					eval('(' + fieldStr + ')')
				} else {
					if (item.value.indexOf('defaultData') != -1 || item.value.indexOf('formData') != -1) {
						let fieldStr = 'that.' + item.field + '= that.' + item.value
						eval('(' + fieldStr + ')')
					} else {
						let fieldStr = 'that.' + item.field + "= '" + item.value + "'"
						eval('(' + fieldStr + ')')
					}
				}
			})
		},
		// 是否需要事务
		setFlowByTrans() {
			this.transFlag = true
		},
		emitButtonEventHandler(key) {
			// 前置事件
			this.doBeforeScript().then(result => {
				if (result) {
					this.emitEventHandler(key)
				}
			})
		},
		/**
		 * 前置脚本
		 */
		async doBeforeScript() {
			if (this.flowBtn.beforeScript != null) {
				let this_ = this
				let that = this
				let doFunction = eval('(' + this.flowBtn.beforeScript + ')')
				try {
					await doFunction()
					return true
				} catch (e) {
					notice.toast(e.message)
					return false
				}
			}
			return true
		},
		/**
		 * 保存表单
		 * @param typeY			expression为true时的保存类型
		 * @param typeN			expression为false时的保存类型
		 * @param expression	表达式
		 * 说明：如果表达式为空，则按照第一个参数进行保存
		 */
		saveFormData(typeY, typeN, expression) {
			let type
			if (!expression) {
				type = typeY
			} else {
				if (expression.indexOf('formData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
				}
				let that = this
				let conditional = eval(expression)
				if (conditional) {
					type = typeY
				} else {
					type = typeN
				}
			}

			// 具体业务保存
			this.saveForm(type)
		},
		/**
		 * 更新流程变量
		 * @param flowVariable  流程变量
		 * @param value 		值
		 * @param expression 	表达式
		 */
		updateFlowVariable(flowVariable, value, expression) {
			let variable = ''
			if (typeof expression === 'undefined') {
				if (value.indexOf('defaultData') != -1 || value.indexOf('formData') != -1) {
					if (value.indexOf('formData') != -1) {
						value = value.replace(/formData./g, '')
						variable = this.formData[value]
					}
					if (value.indexOf('defaultData') != -1) {
						value = value.replace(/defaultData./g, '')
						variable = this.defaultData[value]
					}
				} else {
					variable = value
				}
			} else {
				if (expression.indexOf('formData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
				}
				let that = this
				let this_ = this
				let conditional = eval(expression)
				if (conditional) {
					if (value.indexOf('defaultData') != -1 || value.indexOf('formData') != -1) {
						if (value.indexOf('formData') != -1) {
							value = value.replace(/formData./g, '')
							variable = this.formData[value]
						}
						if (value.indexOf('defaultData') != -1) {
							value = value.replace(/defaultData./g, '')
							variable = this.defaultData[value]
						}
					} else {
						variable = value
					}
				}
			}

			this.variableMap = Object.assign({}, this.variableMap, {
				[flowVariable]: variable
			})
		},
		/**
		 * 更新流程变量（根据条件赋值）
		 * @param flowVariable  流程变量
		 * @param valueY 		表达式为true时的值
		 * @param valueN 		表达式为false时的值
		 * @param expression 	表达式
		 */
		updateFlowVariableByCond(flowVariable, valueY, valueN, expression) {
			let variable = ''
			if (expression.indexOf('formData') != -1) {
				expression = expression.replace(/formData/g, 'that.formData')
			}
			let that = this
			let this_ = this
			let conditional = eval(expression)
			if (conditional) {
				if (valueY.indexOf('defaultData') != -1 || valueY.indexOf('formData') != -1) {
					if (valueY.indexOf('formData') != -1) {
						valueY = valueY.replace(/formData./g, '')
						variable = this.formData[valueY]
					}
					if (valueY.indexOf('defaultData') != -1) {
						valueY = valueY.replace(/defaultData./g, '')
						variable = this.defaultData[valueY]
					}
				} else {
					variable = valueY
				}
			} else {
				if (valueN.indexOf('defaultData') != -1 || valueN.indexOf('formData') != -1) {
					if (valueN.indexOf('formData') != -1) {
						valueN = valueN.replace(/formData./g, '')
						variable = this.formData[valueN]
					}
					if (valueN.indexOf('defaultData') != -1) {
						valueN = valueN.replace(/defaultData./g, '')
						variable = this.defaultData[valueN]
					}
				} else {
					variable = valueN
				}
			}

			this.variableMap = Object.assign({}, this.variableMap, {
				[flowVariable]: variable
			})
		},
		/**
		 * 更新流程参数
		 * @param paramName 	流程参数
		 * @param paramValue 	参数值
		 */
		updateFlowParam(paramName, paramValue) {
			if (paramValue.indexOf('formData') != -1) {
				paramValue = paramValue.replace(/formData./g, '')
				this.flowParams[paramName] = this.formData[paramValue]
			} else if (paramValue.indexOf('defaultData') != -1) {
				paramValue = paramValue.replace(/defaultData./g, '')
				this.flowParams[paramName] = this.defaultData[paramValue]
			} else {
				this.flowParams[paramName] = paramValue
			}
		},
		/**
		 * 更新业务状态
		 * @param type 			更新类型：expression--表达式，variable--变量
		 * @param stateField 	状态字段
		 * @param stateY 		expression为true时的状态，或者变量状态
		 * @param stateN 		expression为false时的状态
		 * @param expression 	表达式
		 * 说明：
		 * 1、更新类型为expression时，所有参数必传；
		 * 2、更新类型为variable时，前三个参数必传，其余可为空；
		 */
		updateBusinessState(stateField, stateY, stateN, expression) {
			if (typeof expression === 'undefined') {
				if (stateField.indexOf('formData') != -1) {
					stateField = stateField.replace(/formData./g, '')
					this.formData[stateField] = stateY
				}
			} else {
				let that = this
				let this_ = this
				if (expression.indexOf('formData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
				}
				let conditional = eval(expression)
				if (conditional) {
					if (stateField.indexOf('formData') != -1) {
						stateField = stateField.replace(/formData./g, '')
						this.formData[stateField] = stateY
					}
				} else {
					if (stateField.indexOf('formData') != -1) {
						stateField = stateField.replace(/formData./g, '')
						this.formData[stateField] = stateN
					}
				}
			}

			// 具体业务更新状态
			this.updateState()
		},
		/**
		 * 更新表单（支持多个字段）
		 * @param {Object} params
		 */
		updateFormFields(params) {
			let that = this
			for (const [key, value] of Object.entries(params)) {
				if (key in that.formData) {
					that.formData[key] = value
				}
			}

			// 具体业务更新
			this.updteForm()
		},
		/**
		 * 更新表单（单个字段）
		 * @param targetField  目标字段
		 * @param value 	   值
		 * @param expression   表达式
		 */
		updateFormElement(targetField, value, expression) {
			if (typeof expression === 'undefined') { // 直接赋值
				if (targetField.indexOf('formData') != -1) {
					targetField = targetField.replace(/formData./g, '')
					if (value.indexOf('formData') != -1) {
						value = value.replace(/formData./g, '')
						this.formData[targetField] = this.formData[value]
					} else if (value.indexOf('defaultData') != -1) {
						value = value.replace(/defaultData./g, '')
						this.formData[targetField] = this.defaultData[value]
					} else {
						this.formData[targetField] = value
					}
				}
			} else { // 表达式赋值
				if (expression.indexOf('formData') != -1) {
					expression = expression.replace(/formData/g, 'that.formData')
				}
				let that = this
				let this_ = this
				let conditional = eval(expression)
				if (conditional) {
					if (targetField.indexOf('formData') != -1) {
						targetField = targetField.replace(/formData./g, '')
						if (value.indexOf('formData') != -1) {
							value = value.replace(/formData./g, '')
							this.formData[targetField] = this.formData[value]
						} else if (value.indexOf('defaultData') != -1) {
							value = value.replace(/defaultData./g, '')
							this.formData[targetField] = this.defaultData[value]
						} else {
							this.formData[targetField] = value
						}
					}
				}
			}

			// 具体业务更新
			this.updteForm()
		},
		emitEventHandler(actionName) {
			const buttonType = actionName
			switch (buttonType) {
				case 'agree': // 同意
				case 'oppose': // 反对
					this.handleDirectActionEvent(actionName)
					break
				case 'rejectToPrevious': // 驳回上一步
				case 'rejectToStart': // 驳回发起人
				case 'reject': // 驳回
					this.handleDirectActionEvent(actionName)
					break
				case 'endProcess': // 终止流程
					this.handleDirectActionEvent(actionName)
					break
				default:
					break
			}
		},
		/**
		 * 直接同意流程
		 * @param {*} actionName
		 */
		handleDirectActionEvent(actionName) {
			// 审批意见处理
			if (!this.opinion) {
				if (actionName == 'agree') {
					this.opinion = this.$t('common.buttons.agree')
				} else if (actionName.indexOf('reject') != -1) {
					this.opinion = this.$t('common.buttons.reject')
				}
			}
			const params = {
				opinion: this.opinion
			}

			this.handleActionEvent(actionName, params)
		},
		/**
		 * 处理按钮事件
		 * @param {*} actionName
		 * @param {*} params
		 */
		handleActionEvent(actionName, params) {
			if (actionName === 'agree' ||
				actionName === 'oppose' ||
				actionName === 'rejectToPrevious' ||
				actionName === 'rejectToStart' ||
				actionName === 'reject'
			) {
				this.handleComplete(actionName, params)
			} else if (actionName === 'endProcess') {
				this.handleDoEndProcess(params)
			}
		},
		handleComplete(actionName, params = {}) {
			uni.showLoading({
				title: "请稍后",
				mask: true
			})
			params.transFlag = this.transFlag
			params.taskId = this.taskId
			params.variableMap = this.variableMap
			params.nodeUsers = JSON.stringify(this.flowParams.nodeUsers)
			// 驳回处理
			if (actionName == 'rejectToStart' || actionName == 'rejectToPrevious' || actionName == 'reject') {
				params.backHandMode = 'normal'
				params.destination = this.flowParams.destination
			}

			let requestMethod = null

			switch (actionName) {
				case 'agree':
				case 'accept':
				case 'delay':
				case 'hang':
				case 'transfer':
				case 'major':
					requestMethod = agree
					break
				case 'oppose':
					requestMethod = oppose
					break
				case 'rejectToPrevious':
					requestMethod = rejectToPrevious
					break
				case 'rejectToStart':
					requestMethod = rejectToStarter
					break
				case 'reject':
					requestMethod = reject
					break
				default:
					break
			}
			if (!requestMethod) {
				return
			}

			requestMethod(params).then(response => {
				uni.hideLoading()
				this.handleResponse(actionName, response)
			})
		},
		handleResponse(actionName, response) {
			notice.success(response.message)
			// 执行后置脚本
			this.doAfterScript()
		},
		/**
		 * 处理终止任务
		 * @param {*} params
		 */
		handleDoEndProcess(params) {
			doEndProcess({
				taskId: this.taskId,
				endReason: params.opinion
			}).then(response => {
				notice.success(response.message)
				// 执行后置脚本
				this.doAfterScript()
			})
		},
		/**
		 * 后置脚本
		 */
		doAfterScript() {
			if (this.flowBtn.afterScript != null) {
				let this_ = this
				let that = this
				let doFunction = eval('(' + this.flowBtn.afterScript + ')')
				doFunction()
				utilities.back(this.sourceType)
				return true
			}
			utilities.back(this.sourceType)
			return true
		}
	}
}
